package com.yuntongxun.ecdemo.voicechat.ui.activity;

import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;

import com.loopj.android.http.RequestParams;
import com.yuntongxun.ecdemo.R;
import com.yuntongxun.ecdemo.common.CCPAppManager;
import com.yuntongxun.ecdemo.common.utils.ToastUtil;
import com.yuntongxun.ecdemo.storage.ContactSqlManager;
import com.yuntongxun.ecdemo.ui.contact.ECContacts;
import com.yuntongxun.ecdemo.voicechat.api.ApiConstants;
import com.yuntongxun.ecdemo.voicechat.bean.UserInfo;
import com.yuntongxun.ecdemo.voicechat.comman.Contants;
import com.yuntongxun.ecdemo.voicechat.listeners.IRecyclerViewItemListener;
import com.yuntongxun.ecdemo.voicechat.listeners.LoadMoreClickListener;
import com.yuntongxun.ecdemo.voicechat.loading.ILoadView;
import com.yuntongxun.ecdemo.voicechat.loading.ILoadViewImpl;
import com.yuntongxun.ecdemo.voicechat.presenter.ICommonRequestPresenter;
import com.yuntongxun.ecdemo.voicechat.presenter.impl.CommonRequestPresenterImpl;
import com.yuntongxun.ecdemo.voicechat.ui.adapter.MemberAdapter;
import com.yuntongxun.ecdemo.voicechat.util.JsonHelper;
import com.yuntongxun.ecdemo.voicechat.util.NetUtils;
import com.yuntongxun.ecdemo.voicechat.util.iview.ICommonViewUi;
import com.yuntongxun.ecdemo.voicechat.view.SearchEditText;
import com.yuntongxun.ecdemo.voicechat.view.headerfooterrecyclerview.ExStaggeredGridLayoutManager;
import com.yuntongxun.ecdemo.voicechat.view.headerfooterrecyclerview.HeaderAndFooterRecyclerViewAdapter;
import com.yuntongxun.ecdemo.voicechat.view.headerfooterrecyclerview.HeaderSpanSizeLookup;
import com.yuntongxun.ecdemo.voicechat.view.headerfooterrecyclerview.OnRecyclerViewScrollListener;
import com.yuntongxun.ecdemo.voicechat.view.headerfooterrecyclerview.RecyclerViewUtils;
import com.yuntongxun.ecsdk.ECDevice;
import com.yuntongxun.ecsdk.ECError;
import com.yuntongxun.ecsdk.ECUserState;
import com.yuntongxun.ecsdk.SdkErrorCode;

import java.util.ArrayList;
import java.util.List;

import butterknife.InjectView;
import butterknife.OnClick;

/**
 * 搜索成员
 */
public class SearchMembersActivity extends BaseChatActivity implements ICommonViewUi, IRecyclerViewItemListener, LoadMoreClickListener, SwipeRefreshLayout.OnRefreshListener {

    @InjectView(R.id.swipe_refresh_layout)
    public SwipeRefreshLayout swipeRefreshLayout;

    @InjectView(R.id.recycler_view)
    public RecyclerView recyclerView;

    private HeaderAndFooterRecyclerViewAdapter adapter;
    private ExStaggeredGridLayoutManager staggeredGridLayoutManager;
    private List<UserInfo> mResultList = new ArrayList<UserInfo>();

    private ICommonRequestPresenter iCommonRequestPresenter = null;

    private ILoadView iLoadView = null;

    private View loadMoreView = null;

    private boolean isRequesting = false;//标记，是否正在刷新

    private int mCurrentPage = 0;

    @InjectView(R.id.et_search_view)
    SearchEditText searchEditText;

    @Override
    protected boolean isBindEventBusHere() {
        return false;
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.activity_search_members;
    }

    @Override
    protected void initViewsAndEvents() {

        iCommonRequestPresenter = new CommonRequestPresenterImpl(mContext, this);

        iLoadView = new ILoadViewImpl(mContext, this);

        loadMoreView = iLoadView.inflate();

        swipeRefreshLayout.setOnRefreshListener(this);
        recyclerView.addOnScrollListener(new MyScrollListener());

        refreshListView();

        //第一次进来时刷新
        if (NetUtils.isNetworkConnected(mContext)) {
            if (null != swipeRefreshLayout) {

                swipeRefreshLayout.postDelayed(new Runnable() {
                    @Override
                    public void run() {

                        swipeRefreshLayout.setRefreshing(true);

                        toRequest(ApiConstants.EventTags.REFRESH_LIST_EVENT);
                    }
                }, ApiConstants.Integers.PAGE_LAZY_LOAD_DELAY_TIME_MS);
            }
        }
    }

    /**
     * 解析结果
     *
     * @param result
     * @return
     */
    public List<UserInfo> parseResult(String result) {
//        数据解析
        JsonHelper<UserInfo> dataParser = new JsonHelper<UserInfo>(
                UserInfo.class);
        return dataParser.getDatas(
                result, "list");

    }

    @Override
    public void toRequest(int eventTag) {

        if (eventTag == ApiConstants.EventTags.REFRESH_LIST_EVENT) {
            //刷新

            if (!NetUtils.isNetworkAvailable(mContext)) {
                showToastShort(Contants.NetStatus.NETDISABLE);
                swipeRefreshLayout.setRefreshing(false);
                return;
            }

            mCurrentPage = 1;

            RequestParams map = new RequestParams();
            map.put("page", "" + mCurrentPage);
            map.put("pageSize", "30");
            iCommonRequestPresenter.request(ApiConstants.EventTags.REFRESH_LIST_EVENT, mContext, ApiConstants.Urls.ACCOUNT_LIST, map);

        } else if (eventTag == ApiConstants.EventTags.LOAD_MORE_LIST_EVENT) {
            //加载更多

            if (isRequesting)
                return;

            if (!NetUtils.isNetworkAvailable(mContext)) {
                showToastShort(Contants.NetStatus.NETDISABLE);
                iLoadView.showErrorView(loadMoreView);
                return;
            }

            if (mResultList.size() < ApiConstants.Request.PAGE_NUMBER) {
                return;
            }

            mCurrentPage++;

            iLoadView.showLoadingView(loadMoreView);

            RequestParams map = new RequestParams();
            map.put("page", "" + mCurrentPage);
            map.put("pageSize", "30");
            iCommonRequestPresenter.request(ApiConstants.EventTags.LOAD_MORE_LIST_EVENT, mContext, ApiConstants.Urls.ACCOUNT_LIST, map);

        }
    }

    @Override
    public void getRequestData(int eventTag, String result) {

        if (eventTag == ApiConstants.EventTags.REFRESH_LIST_EVENT) {
            //下拉刷新

            List<UserInfo> resultList = parseResult(result);

            mResultList.clear();
            mResultList.addAll(resultList);
            List<String> ids=new ArrayList<>();
            for (int i=0;i<mResultList.size();i++){
                ids.add(mResultList.get(i).getId());
            }
            String[] array = new String[ids.size()];
            ids.toArray(array);


            List<ECContacts> contacts = new ArrayList<>();
            for (int i = 0; i < resultList.size(); i++) {
                ECContacts contact = new ECContacts();
                UserInfo info = mResultList.get(i);
                StringBuffer message= new StringBuffer();
                message.append("{\"result\":" );
                message.append("{\"accountName\":\"" + info.getAccountName() + "\",");
                message.append("\"nickName\":\"" + info.getNickName() + "\",");
                message.append("\"id\":\"" + info.getId() + "\",");
                message.append("\"gender\":\"" + info.getGender() + "\",");
                message.append("\"age\":\"" + info.getAge() + "\",");
                message.append("\"country\":\"" + info.getCountry() + "\",");
                message.append("\"nativeLanguage\":\"" + info.getNativeLanguage() + "\",");
                message.append("\"learningLanguage\":\"" + info.getLearningLanguage() + "\"}}");
//                LogUtil.e("memeber",message.toString());
//                String message = info.getNickName() + "-" + info.getGender() + "-" + info.getAge() + "-" + info.getCountry() + "-" + info.getNativeLanguage() + "-" + info.getLearningLanguage();
                contact.setNickname(mResultList.get(i).getNickName() + "(" + message.toString()+ ")");
                contact.setNickname(mResultList.get(i).getNickName() + "(" + message + ")");
                contact.setContactid(mResultList.get(i).getId());
                contacts.add(contact);
            }
            ContactSqlManager.insertContacts(contacts);
            refreshListView();
            asyncState(array);

        } else if (eventTag == ApiConstants.EventTags.LOAD_MORE_LIST_EVENT) {
            //加载更多

            List<UserInfo> resultList = parseResult(result);

            mResultList.addAll(resultList);
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onRequestSuccessException(int eventTag, String msg) {

        if (eventTag == ApiConstants.EventTags.LOAD_MORE_LIST_EVENT) {

            if (mCurrentPage > 1)
                mCurrentPage--;

            iLoadView.showErrorView(loadMoreView);
        }

        showToastShort(msg);
    }

    @Override
    public void onRequestFailureException(int eventTag, String msg) {

        if (eventTag == ApiConstants.EventTags.LOAD_MORE_LIST_EVENT) {

            if (mCurrentPage > 1)
                mCurrentPage--;

            iLoadView.showErrorView(loadMoreView);
        }

        showToastShort(msg);
    }

    @Override
    public void isRequesting(int eventTag, boolean status) {
        isRequesting = status;

        if (!status) {
            swipeRefreshLayout.setRefreshing(false);
        }
    }


    @Override
    public void clickLoadMoreData() {
        toRequest(ApiConstants.EventTags.LOAD_MORE_LIST_EVENT);
    }

    @Override
    public void onItemClick(int position) {
//        Toast.makeText(mContext, "onItemClick>" + position, Toast.LENGTH_SHORT).show();

        UserInfo info = mResultList.get(position);
        ECContacts mContacts = ContactSqlManager.getCacheContact(info.getId());
        if (mContacts == null) {
            mContacts = new ECContacts(info.getId());
            mContacts.setNickname(info.getNickName());
        }

        if (mContacts == null) {
            ToastUtil.showMessage(R.string.contact_none);
            return;
        }
//        String message=info.getNickName()+"-"+info.getGender()+"-"+info.getAge()+"-"+info.getCountry()+"-"+info.getNativeLanguage()+"-"+info.getLearningLanguage();
//        CCPAppManager.startChattingAction(getActivity(), mContacts.getContactid()+"("+message+")", mContacts.getNickname(), true);
        CCPAppManager.startChattingAction(mContext, mContacts.getContactid(), mContacts.getNickname(), true);
        setResult(RESULT_OK);
    }

    public void refreshListView() {

        MemberAdapter mIntermediary = new MemberAdapter(mContext, mResultList, this);

        adapter = new HeaderAndFooterRecyclerViewAdapter(mIntermediary);

        recyclerView.setAdapter(adapter);

        if (mResultList.size() >= ApiConstants.Request.PAGE_NUMBER) {

            RecyclerViewUtils.setFooterView(recyclerView, loadMoreView);
        }
        staggeredGridLayoutManager = new ExStaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL);

        staggeredGridLayoutManager.setSpanSizeLookup(new HeaderSpanSizeLookup((HeaderAndFooterRecyclerViewAdapter) recyclerView.getAdapter(), staggeredGridLayoutManager.getSpanCount()));

        recyclerView.setLayoutManager(staggeredGridLayoutManager);
    }

    @Override
    public void onRefresh() {
        toRequest(ApiConstants.EventTags.REFRESH_LIST_EVENT);
    }

    @OnClick(R.id.tv_top_right)
    public void onClick() {
        //点击搜索
        String searchTxt = searchEditText.getText().toString();

        if (!NetUtils.isNetworkAvailable(mContext)) {
            showToastShort(Contants.NetStatus.NETDISABLE);
            swipeRefreshLayout.setRefreshing(false);
            return;
        }

        mCurrentPage = 1;

        RequestParams map = new RequestParams();
        map.put("page", "" + mCurrentPage);
        map.put("pageSize", "30");
        map.put("keyword", "" + searchTxt);

        iCommonRequestPresenter.request(ApiConstants.EventTags.REFRESH_LIST_EVENT, mContext, ApiConstants.Urls.ACCOUNT_LIST, map);


    }

    public class MyScrollListener extends OnRecyclerViewScrollListener {

        @Override
        public void onScrollUp() {

        }

        @Override
        public void onScrollDown() {

        }

        @Override
        public void onBottom() {
            toRequest(ApiConstants.EventTags.LOAD_MORE_LIST_EVENT);
        }

        @Override
        public void onMoved(int distanceX, int distanceY) {

        }
    }

    private void asyncState(String[] id){
        if (id==null||id.length==0){
            return;
        }
        ECDevice.getUsersState(id, new ECDevice.OnGetUsersStateListener() {
            @Override
            public void onGetUsersState(ECError ecError, ECUserState... ecUserStates) {
                if (ecError.errorCode == SdkErrorCode.REQUEST_SUCCESS && ecUserStates != null) {
                    for (int i=0;i<ecUserStates.length;i++){
                        ECUserState userState =ecUserStates[i];
                        for (int j=0;j<mResultList.size();j++){
                            if (userState.getUserId().equals(mResultList.get(j).getId())){
                                mResultList.get(j).setState(userState.isOnline()?0:1);
                            }
                        }
                    }
                    adapter.notifyDataSetChanged();
                }
            }
        });
    }
}